package com.sk.weichat.ui.groupchat;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.sk.weichat.R;
import com.sk.weichat.Reporter;
import com.sk.weichat.adapter.CommonRecyclerAdapter;
import com.sk.weichat.adapter.SelectContacts;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.helper.AvatarHelper;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.sortlist.BaseSortModel;
import com.sk.weichat.sortlist.SideBar;
import com.sk.weichat.sortlist.SortHelper;
import com.sk.weichat.ui.base.EasyFragment;
import com.sk.weichat.util.AsyncUtils;
import com.sk.weichat.util.ListUtil;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.view.ClearEditText;
import com.sk.weichat.view.MaxTextTwoLengthFilter;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;


public class SelectContactsFragment extends EasyFragment {

   private ClearEditText mEditText;
    private RecyclerView recy_contacts;
    private TextView mTextDialog;
    private TextView tvNoFriend;
    private TextView tvBestFit;
    private  SideBar mSideBar;
    private CommonRecyclerAdapter mAdapter;
    private List<BaseSortModel<Friend>> mSortFriends = new ArrayList<>();
    private List<BaseSortModel<Friend>> mSearchSortFriends = new ArrayList<>();

    private String mLoginUserId;
    private int lvScrollPosition;
    private Set<String> mExistIds = new HashSet<>();
    private  List<String> mSelectPositions = new ArrayList<>();
    private boolean isSearch;

    // 是否是通过单人聊天快速创建的群组
    private boolean mQuicklyCreate;
    //     快速建群时聊天对象的id与备注名/昵称
    private String mQuicklyId;
    private String mQuicklyName;
    private boolean isAltFriends;


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mExistIds = ((TabSelectContactsActivity) activity).getExistIds();
        mSelectPositions =  ((TabSelectContactsActivity) activity).getSelectPositions();

        mQuicklyCreate = ((TabSelectContactsActivity) activity).isQuicklyCreate();
        mQuicklyId = ((TabSelectContactsActivity) activity).getQuicklyId();
        mQuicklyName = ((TabSelectContactsActivity) activity).getQuicklyName();
        isAltFriends = ((TabSelectContactsActivity) activity).isAltFriends();

    }
    public static  SelectContactsFragment getInstance() {
        SelectContactsFragment hf = new SelectContactsFragment();
//        Bundle args = new Bundle();
//        hf.setArguments(args);
        return hf;
    }
    @Override
    protected int inflateLayoutId() {
        return R.layout.fragment_select_contacts;
    }

    @Override
    protected void onActivityCreated(Bundle savedInstanceState, boolean createView) {
        initView();
        loadData();

    }
    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
    private void initView(){
        tvNoFriend = findViewById(R.id.tv_no_label_friend);
        tvBestFit = findViewById(R.id.tv_best_fit_friend);
        mEditText = findViewById(R.id.search_et);
        mEditText.setHint("请输入昵称或备注名");

        mEditText.setFilters(new InputFilter[]{new MaxTextTwoLengthFilter(24)});
        mEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                mSearchSortFriends.clear();
                String str = mEditText.getText().toString();
                if (TextUtils.isEmpty(str)) {
                    isSearch = true;
                    loadData();
                    tvNoFriend.setVisibility(View.GONE);
                    tvBestFit.setVisibility(View.GONE);
                    mSideBar.setVisibility(View.VISIBLE);
                    return;
                }
                for (int i = 0; i < mSortFriends.size(); i++) {
                    String name = !TextUtils.isEmpty(mSortFriends.get(i).getBean().getRemarkName()) ?
                            mSortFriends.get(i).getBean().getRemarkName() : mSortFriends.get(i).getBean().getNickName();
                    if (name.contains(str)) {
                        // 符合搜索条件的好友
                        mSearchSortFriends.add((mSortFriends.get(i)));
                    }
                }
                if (mSearchSortFriends.size()>0){
                    tvNoFriend.setVisibility(View.GONE);
                    tvBestFit.setVisibility(View.VISIBLE);
                }else {
                    tvBestFit.setVisibility(View.GONE);
                    tvNoFriend.setVisibility(View.VISIBLE);
                    tvNoFriend.setText("不存在“"+str+"”好友");
                }
                mSortFriends.clear();
                mSortFriends.addAll(mSearchSortFriends);
                mAdapter.notifyDataSetChanged();
            }
        });

        recy_contacts = findViewById(R.id.recy_contacts);
        LinearLayoutManager manager = new LinearLayoutManager(mActivity);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recy_contacts.setLayoutManager(manager);
        initListAdapter();
        mLoginUserId = coreManager.getSelf().getUserId();
        mSideBar = findViewById(R.id.sidebar);
        mTextDialog = findViewById(R.id.text_dialog);
        mSideBar.setTextView(mTextDialog);
        mSideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                // 该字母首次出现的位置
                int position = ListUtil.getPositionForSection(mSortFriends, s.charAt(0));
                if (position != -1) {
                    manager.scrollToPositionWithOffset(position + 1, 0);
                    showTextDialog(s);
                }
            }
        });
        recy_contacts.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int visibleItemCount = manager.getChildCount();//屏幕可见item数
                int totalItemCount = manager.getItemCount();//总item数
                int pastVisibleItems = manager.findFirstVisibleItemPosition();//屏幕显示的第一个item的下标index
                if (pastVisibleItems > 1 && visibleItemCount + pastVisibleItems < totalItemCount) {
                    int firstIndex = pastVisibleItems - 1;
                    String firstStr = ListUtil.getFirstStr(mSortFriends, firstIndex);
                    mSideBar.searchByFirstStr(firstStr);
                    String strLast = ListUtil.getFirstStr(mSortFriends, pastVisibleItems - 2);
                    String strSec = ListUtil.getFirstStr(mSortFriends, pastVisibleItems);
                    if (lvScrollPosition < firstIndex) {
                        if (!firstStr.equals(strLast)) {
                            showTextDialog(firstStr);
                        }
                    } else if (lvScrollPosition > firstIndex) {
                        if (!firstStr.equals(strSec)) {
                            showTextDialog(firstStr);
                        }
                    }
                }
                lvScrollPosition = pastVisibleItems - 1;
            }
        });
    }


    //初始化适配器及事件
    private void initListAdapter() {
        mAdapter = new CommonRecyclerAdapter(R.layout.row_select_contacts, mSortFriends) {
            @Override
            public void convert(BaseViewHolder holder, int position) {
//                position=position-1;//添加了一个头部
                TextView categoryTitleTv = holder.getView(R.id.catagory_title);
                ImageView avatar_img = holder.getView(R.id.avatar_img);
                TextView nick_name_tv = holder.getView(R.id.user_name_tv);
                CheckBox check_box = holder.getView(R.id.check_box);

                // 根据position获取分类的首字母的Char ascii值
                int section = ListUtil.getSectionForPosition(mSortFriends, position);
                // 如果当前位置等于该分类首字母的Char的位置 ，则认为是第一次出现
                if (position == ListUtil.getPositionForSection(mSortFriends, section)) {
                    categoryTitleTv.setVisibility(View.VISIBLE);
                    categoryTitleTv.setText(mSortFriends.get(position).getFirstLetter());
                } else {
                    categoryTitleTv.setVisibility(View.GONE);
                }
                Friend friend = mSortFriends.get(position).getBean();
                if (friend.getUserId().equals(Friend.ID_SYSTEM_MESSAGE)) {
                    avatar_img.setImageResource(R.mipmap.ic_service);
                } else {
                    AvatarHelper.getInstance().displayAvatar(friend.getUserId(), avatar_img, true);
                }
                // 昵称
                nick_name_tv.setText(!TextUtils.isEmpty(friend.getRemarkName()) ? friend.getRemarkName() : friend.getNickName());
                check_box.setChecked(false);
                if (friend.getStatus() == 100) {
                    check_box.setChecked(true);
                } else {
                    check_box.setChecked(false);
                }

                if (mQuicklyCreate) {
                    if (friend.getUserId().equals(mLoginUserId) || friend.getUserId().equals(mQuicklyId)) {
                        check_box.setChecked(true);
                    }
                }
            }
        };
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                if (isAltFriends&&mSortFriends.get(position).getBean().getStatus()!=100){
                    if (mSelectPositions.size()>=10){
                        ToastUtil.showToast(mActivity,"最多能@10个人");
                        return;
                    }
                }
                if (mSelectPositions.size()>=20&&mSortFriends.get(position).getBean().getStatus()!=100){
                    ToastUtil.showToast(mActivity,"一次只能选择20人");
                }else {
                    Friend friend = mSortFriends.get(position).bean;
                    if (mQuicklyCreate) {
                        if (friend.getUserId().equals(mLoginUserId)) {
                            ToastUtil.showToast(mActivity, getString(R.string.tip_cannot_remove_self));
                            return;
                        } else if (friend.getUserId().equals(mQuicklyId)) {
                            ToastUtil.showToast(mActivity, getString(R.string.tip_quickly_group_cannot_remove) + mQuicklyName);
                            return;
                        }
                    }

                    for (int i = 0; i < mSortFriends.size(); i++) {
                        if (mSortFriends.get(i).getBean().getUserId().equals(friend.getUserId())) {
                            if (friend.getStatus() != 100) {
                                friend.setStatus(100);
                                mSortFriends.get(i).getBean().setStatus(100);
                                SelectContacts contacts = new SelectContacts();
                                contacts.setUserId(friend.getUserId());
                                contacts.setSelect(true);
                                EventBus.getDefault().post(contacts);
                            } else {
                                friend.setStatus(101);
                                mSortFriends.get(i).getBean().setStatus(101);
                                SelectContacts contacts = new SelectContacts();
                                contacts.setUserId(friend.getUserId());
                                contacts.setSelect(false);
                                EventBus.getDefault().post(contacts);
                            }
                            mAdapter.notifyDataSetChanged();
                        }
                    }
                }
            }
        });
        //禁止RecyclerView的默认动画
        ((SimpleItemAnimator) recy_contacts.getItemAnimator()).setSupportsChangeAnimations(false);
        mAdapter.setHasStableIds(true);
        recy_contacts.setAdapter(mAdapter);
    }
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(SelectContacts contacts) {
        for (int i = 0; i < mSortFriends.size(); i++) {

            if (mSortFriends.get(i).getBean().getUserId().equals(contacts.getUserId())){
                if (contacts.isSelect()){
                    mSortFriends.get(i).getBean().setStatus(100);
                }else {
                    mSortFriends.get(i).getBean().setStatus(101);
                }

            }
        }
        mAdapter.notifyDataSetChanged();
    }

    private void loadData() {
        if (!isSearch&&!DialogHelper.isShowing()) {
            DialogHelper.showDefaulteMessageProgressDialog(getActivity());
        }
        AsyncUtils.doAsync(this, e -> {
            Reporter.post("加载数据失败，", e);
            AsyncUtils.runOnUiThread(requireContext(), ctx -> {
                DialogHelper.dismissProgressDialog();
                ToastUtil.showToast(ctx, R.string.data_exception);
            });
        }, c -> {
            final List<Friend> friends = FriendDao.getInstance().getFriendsGroupChat(mLoginUserId);
            if (mQuicklyCreate) {
                Friend friend = new Friend();
                friend.setUserId(mLoginUserId);
                friend.setNickName(coreManager.getSelf().getNickName());
                friends.add(0, friend);
            }
            Map<String, Integer> existMap = new HashMap<>();
            List<BaseSortModel<Friend>> sortedList;
            if (mExistIds!=null){
                sortedList = SortHelper.toSortedModelList(friends, existMap, f -> {
                    if (isExist(f)) {
                        // 过滤掉已经在群里的，
                        return null;
                    } else {
                        return f.getShowName();
                    }
                });
            }else {
                 sortedList = SortHelper.toSortedModelList(friends, existMap, Friend::getShowName);
            }
            c.uiThread(r -> {
                DialogHelper.dismissProgressDialog();
                mSideBar.setExistMap(existMap);
                if (!ListUtil.isListEmpty(sortedList)) {
                    mSideBar.searchByFirstStr(sortedList.get(0).getFirstLetter());
                }
                if (mSortFriends != null) {
                    mSortFriends.clear();
                }
                if (sortedList != null && sortedList.size() > 0) {
                    mSideBar.setVisibility(View.VISIBLE);
                    mSideBar.searchByFirstStr(sortedList.get(0).getFirstLetter());
                    tvNoFriend.setVisibility(View.GONE);
                } else {
                    mSideBar.setVisibility(View.GONE);
                    tvNoFriend.setVisibility(View.VISIBLE);
                    tvNoFriend.setText("暂无好友");
                }

                if (mSelectPositions!=null&&mSelectPositions.size()!=0){
                    for (int i=0;i<sortedList.size();i++){
                        for (int j=0;j<mSelectPositions.size();j++){
                            if (sortedList.get(i).getBean().getUserId().equals(mSelectPositions.get(j))){
                                sortedList.get(i).getBean().setStatus(100);
                            }
                        }
                    }
                }
                mSortFriends.addAll(sortedList);
                mAdapter.notifyDataSetChanged();

                if (mQuicklyCreate) {
                    for (int i = 0; i < mSortFriends.size(); i++) {
                        Friend friend = mSortFriends.get(i).getBean();
                        if (friend.getUserId().equals(mLoginUserId) || friend.getUserId().equals(mQuicklyId)) {
                            SelectContacts contacts = new SelectContacts();
                            contacts.setUserId(friend.getUserId());
                            contacts.setSelect(true);
                            EventBus.getDefault().post(contacts);
                        }
                    }
                }
            });
        });
    }
    //显示索引字母
    private void showTextDialog(String s) {
        mTextDialog.setText(s);
        mTextDialog.setVisibility(View.VISIBLE);
        mHandler.removeMessages(0);
        mHandler.sendEmptyMessageDelayed(0, 100);
    }
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    AlphaAnimation aa = new AlphaAnimation(1.0f, 0.0f);//创建一个AlphaAnimation 对象，渐变从1->0
                    aa.setDuration(1000);//设置持续时间
                    aa.setFillAfter(true);
                    mTextDialog.startAnimation(aa);
                    mTextDialog.setVisibility(View.GONE);
                    break;
            }
            super.handleMessage(msg);
        }
    };
    /**
     * 是否存在已经在那个房间的好友
     */
    private boolean isExist(Friend friend) {
        return mExistIds.contains(friend.getUserId());
    }

}
